#coding:utf-8
import re

class Pubtable():
    def __init__(self,**params):
        self.mul_ls = params['mul_ls']
        self.conf = params['conf']
        self.type = params['type']
        if self.type == '3':
            self.sec = self.conf['achivement_sec_common']
        else:
            type_sec = self.conf['type_sec'][self.type]
            self.sec = self.conf[type_sec]

    def inside_for_mul_concat(self,pre_dict,now_dict,key):
        temp_ls = pre_dict['value']
        temp_ls_num = []
        for num,num_data in enumerate(now_dict['value']):
            if num_data not in temp_ls:
                temp_ls_num.append(num)
        if key == 1:
            tt_dict_key = ['value','x','y','standard']
        elif key == 2:
            tt_dict_key = ['value','x','y','pre']
        for num in temp_ls_num:
            for tt_dict_keyi in tt_dict_key:
                pre_dict[tt_dict_keyi].append(now_dict[tt_dict_keyi][num])

        return pre_dict


    def inside_for_mul_concat_pre_get_use(self,standard,data):
        NeedMatch = self.sec[standard][0]
        NoMatch = self.sec[standard][1]
        tt_ls = []
        for num, value in enumerate(data['value']):
            if re.search(NeedMatch, value) == None or re.search(NoMatch, value) != None:
                continue
            tt_ls.append(num)
        tt_dict = {
            'value': [],
            'x': [],
            'y': [],
            'standard': []
        }
        tt_dict_key = ['value', 'x', 'y', 'standard']
        for num in tt_ls:
            for tt_dict_keyi in tt_dict_key:
                tt_dict[tt_dict_keyi].append(data[tt_dict_keyi][num])
        return tt_dict

    #多表的数据根据原值进行组合，同时利用配置筛选需求字段
    def mul_concat_pre(self,mul_ls):
        out_dict = {}
        key_ls = list(self.sec.keys())
        for table_dict in mul_ls:
            for key in table_dict:
                if '※' not in table_dict[key]['standard'][0]:
                    standard = table_dict[key]['standard'][0]
                else:
                    pre,opre = table_dict[key]['standard'][0].split('※')
                    if pre in self.conf['title_concat']['need_factor']:
                        standard = ''
                        for prei in self.conf['title_concat']['need_factor'][pre]:
                            if opre == prei[0]:
                                standard = prei[1]
                        if standard == '':
                            standard = opre
                    else:
                        standard = opre
                if re.search('最高限价|预算金额|投资额',standard):
                    obj = re.search('[万亿%]',standard)
                    if obj:
                        table_dict[key]['value'] = [i+'➼'+obj.group() for i in table_dict[key]['value']]
                        table_dict[key]['standard'] = [i.split('（')[0] for i in table_dict[key]['standard']]
                        standard = standard.split('（')[0]
                #标准值不在键中，跳过此键数据
                if standard not in key_ls:
                    continue
                #根据需求配置取值
                table_dict[key] = self.inside_for_mul_concat_pre_get_use(standard, table_dict[key])
                if table_dict[key]['value'] == []:
                    continue
                #根据原值匹配数据
                if key not in out_dict:
                    out_dict[key] = table_dict[key]
                else:
                    pre_dict = out_dict[key]
                    now_dict = table_dict[key]
                    out_dict[key] = self.inside_for_mul_concat(pre_dict,now_dict,1)
        return out_dict

    def inside_for_get_end_data_clear(self,value,key):
        if key in self.conf['clear_func']:
            value = self.conf['clear_func'][key](value)
            return value
        else:
            return value

    # #多表的数据根据标准值进行组合
    def mul_concat_standard(self,mul_concat_pre_data):
        out_dict = {}
        for key in mul_concat_pre_data:
            standard = mul_concat_pre_data[key]['standard'][0]
            tt_dict = {standard:
                           {'value':[],
                            'x':[],
                            'y':[],
                            'pre':[]
                            }
                       }
            tt_dict_key = ['value', 'x', 'y']
            for tt_dict_key in tt_dict_key:
                tt_dict[standard][tt_dict_key] = mul_concat_pre_data[key][tt_dict_key]
            tt_dict[standard]['pre'] = [key] * len(mul_concat_pre_data[key]['standard'])
            #根据标准值匹配数据
            if standard not in out_dict:
                out_dict.update(tt_dict)
            else:
                pre_dict = out_dict[standard]
                now_dict = tt_dict[standard]
                out_dict[standard] = self.inside_for_mul_concat(pre_dict, now_dict,2)
        return out_dict

    #获取最终的数据
    def get_end_data(self,mul_concat_standard_data):
        out_dict = {}
        for i in self.sec.keys():
            if i != '投标要求':
                out_dict[i] = ''
            else:
                out_dict[i] = []
        for key in mul_concat_standard_data:
            if '※' in key:
                continue
            if key != '投标要求':
                out_str = ''
                for struse in mul_concat_standard_data[key]['value']:
                    struse = self.inside_for_get_end_data_clear(struse,key)
                    out_str += str(struse) + ';;'
                out_dict[key] = out_str
            else:
                out_dict[key] = mul_concat_standard_data[key]['value']
        return out_dict


    #特殊组合的处理
    def speciel_concat(self,mul_concat_standard_data):
        out_dict = {}
        for key in mul_concat_standard_data:
            if '※' in key:
                pre,opre = key.split('※')
                if pre in self.conf['title_concat']['need_factor']:
                    for i in self.conf['title_concat']['need_factor'][pre]:
                        if opre == i[0]:
                            if opre not in out_dict:
                                out_dict[i[1]] = mul_concat_standard_data[key]
                            else:
                                tt_ls = ['value','x','y','pre']
                                for tt_lsi in tt_ls:
                                    out_dict[opre][tt_lsi] = out_dict[opre][tt_lsi] + mul_concat_standard_data[key][tt_lsi]
            else:
                out_dict[key] = mul_concat_standard_data[key]
        return  out_dict

    def main(self):
        mul_ls = self.mul_ls
        mul_concat_pre_data = self.mul_concat_pre(mul_ls)
        mul_concat_standard_data = self.mul_concat_standard(mul_concat_pre_data)
        mul_concat_standard_data = self.speciel_concat(mul_concat_standard_data)
        end_data_get = self.get_end_data(mul_concat_standard_data)
        return end_data_get

if __name__ == '__main__':
    from conf import Conf
    from common import *
    KeyValueLs = [{'项目及标段名称': [['蓬安县棚户区改造配套基础设施建设项目（化学厂片区、安置小区外配套基础设施建设工程）监理', 1, 0, '项目名称']], '项目业主': [['四川蓬鑫投资发展有限责任公司', 1, 1, '建设单位']], '项目业主联系电话': [['17383812810', 3, 1, '项目名称']], '招标人': [['四川蓬鑫投资发展有限责任公司', 1, 2, '招标人']], '招标人联系电话': [['17383812810', 3, 2, '建设单位联系电话']], '招标代理机构': [['蓬安县公共资源交易中心', 1, 3, '招标代理单位名称']], '招标代理机构联系电话': [['/', 3, 3, '招标代理单位联系电话']], '开标地点': [['南充市涪江路19号', 1, 4, '开标地点']], '开标时间': [['20201214 - 09:30:00', 3, 4, '开标日期']], '投标最高限价（元）': [['3003864.00', 3, 5, '投标最高限价']]}, {'中标候选人及排序': [['第一', 0, 1, '中标候选人及排序'], ['第二', 0, 2, '中标候选人及排序'], ['第三', 0, 3, '中标候选人及排序']], '中标候选人名称': [['四川建科工程建设管理有限公司', 1, 1, '中标候选人名称'], ['鸿欣建业集团有限公司', 1, 2, '中标候选人名称'], ['成都交大工程建设集团有限公司', 1, 3, '中标候选人名称']], '投标报价（元）': [['2928767.00', 2, 1, '中标金额'], ['2403091.20', 2, 2, '中标金额'], ['2966315.00', 2, 3, '中标金额']], '经评审的投标价（元）': [['2928767.00', 3, 1, '经评审的投标价'], ['2403091.20', 3, 2, '经评审的投标价'], ['2966315.00', 3, 3, '经评审的投标价']], '综合评标得分': [['88.49', 4, 1, '得分'], ['88.34', 4, 2, '得分'], ['81.75', 4, 3, '得分']]},{'招标代理机构': [['蓬安县公共资源交易', 1, 3, '招标代理单位名称']]}]
    with Db('dispose') as conn:
        cursor = conn.cursor()
        params = {
                'conn':conn,
                'cursor':cursor
                  }
        conf = Conf(**params).main()
        params = {
                'conf':conf,
                'pub_data':KeyValueLs,
            'mul_ls':KeyValueLs
                }
        print(Pubtable(**params).main())